package com.kanshu.ksgb.fastread.doudou.module.reader.view

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.graphics.Paint
import android.os.Message
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import com.dl7.recycler.adapter.BaseQuickAdapter
import com.dl7.recycler.adapter.BaseViewHolder
import com.dl7.recycler.helper.RecyclerViewHelper
import com.kanshu.ksgb.fastread.doudou.R
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig
import com.kanshu.ksgb.fastread.doudou.base.basemvp.IGenrialMvpView
import com.kanshu.ksgb.fastread.doudou.common.business.ad.toutiao.WeakHandler
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.BookInfo
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVDefaultManager
import com.kanshu.ksgb.fastread.doudou.common.imageloader.GlideImageLoader
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult
import com.kanshu.ksgb.fastread.doudou.common.net.rx.BaseObserver
import com.kanshu.ksgb.fastread.doudou.common.urlrouter.UrlRouter
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils
import com.kanshu.ksgb.fastread.doudou.common.util.Utils
import com.kanshu.ksgb.fastread.doudou.module.book.bean.ShakeBean
import com.kanshu.ksgb.fastread.doudou.module.book.presenter.BookPresenter
import com.kanshu.ksgb.fastread.doudou.module.book.utils.NeedForAnim
import com.kanshu.ksgb.fastread.doudou.module.book.utils.NeedForAnim.HAND_ANIM_END
import com.kanshu.ksgb.fastread.doudou.module.book.utils.NeedForAnim.HAND_ANIM_START
import com.kanshu.ksgb.fastread.doudou.module.book.utils.NeedForSound
import com.kanshu.ksgb.fastread.doudou.module.book.utils.ShakeListener
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.SettingManager
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.ThemeManager
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.layout_reader_last_page.view.*
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.*

/**
 * Description: 尾页摇一摇
 * @author EvanHe
 * CreateTime: 2018/11/23 11:51
 */
@SuppressLint("ViewConstructor")
class LastPageLabelLayout(val mContext: Context, val bookId: String) : LinearLayout(mContext), WeakHandler.IHandler, IGenrialMvpView<BaseResult<List<BookInfo>>>, View.OnClickListener {
    //手掌上部分
    private var mImgUp: RelativeLayout? = null
    //手掌下部分
    private var mImgDn: RelativeLayout? = null
    // 手掌上部分边线
    private var mImgUpLine: LinearLayout? = null
    //手掌下部分边线
    private var mImgDnLine: LinearLayout? = null
    //手机摇晃的监听器
    private var mShakeListener: ShakeListener? = null
    private var shakeListener: ShakeListener.OnShakeListenerCallBack? = null
    private var mHandler: WeakHandler? = null

    private val bookPresenter = BookPresenter(null)
    private var isNotifyUpdate: Boolean = true // 是否通知书籍更新
    private var writingProcess = "1"
    private var categoryId = "0"

    init {
        orientation = VERTICAL
        gravity = Gravity.CENTER_VERTICAL
        LayoutInflater.from(context).inflate(R.layout.layout_reader_last_page, this)
        mImgUp = findViewById(R.id.shakeImgUp)
        mImgDn = findViewById(R.id.shakeImgDown)
        mImgUpLine = findViewById(R.id.shakeImgUp_line)
        mImgDnLine = findViewById(R.id.shakeImgDown_line)
        back_book_shelf?.paint?.flags = Paint.UNDERLINE_TEXT_FLAG
        notify_book_update.setOnClickListener(this)
        back_book_shelf.setOnClickListener(this)
        shakeDownIv.setOnClickListener(this)
        shakeUpIv.setOnClickListener(this)
        val str: String? = MMKVDefaultManager.getInstance().getBookAttribute(bookId)
        if (!TextUtils.isEmpty(str)) {
            val s = str!!.split("#")
            writingProcess = s.first()
            categoryId = s.last()
        }
        initTheme()
        initShake()
        queryUpdateBook()
        getBookLike()
    }

    private fun initShake() {
        if (mShakeListener == null) {
            mShakeListener = ShakeListener(mContext)
        }
        if (shakeListener == null) {
            shakeListener = ShakeListener.OnShakeListenerCallBack {
                val random = Random().nextInt(6)
                val typedArray = resources.obtainTypedArray(R.array.shake_flower_array)
                shake_flower.setImageResource(typedArray.getResourceId(random, 0))
                typedArray.recycle()
                startShakeAnim() // 开始 摇一摇手掌动画
                mShakeListener?.stop()
                NeedForSound.getInstance().playStartSound()
            }
        }
        mShakeListener?.setOnShakeListener(shakeListener)
        NeedForSound.getInstance().addSound(mContext)
        mHandler = WeakHandler(this)
    }

    private fun initTheme() {
        if (SettingManager.getInstance().isNight) {
            setBackgroundResource(R.drawable.theme_night_bg)
            shakeImgUp.setBackgroundColor(Color.BLACK)
            shakeImgDown.setBackgroundColor(Color.BLACK)
            DisplayUtils.visible(night_mode_trans)
        } else {
            ThemeManager.setReaderTheme(SettingManager.getInstance().readTheme, root_layout)
            ThemeManager.setReaderTheme(SettingManager.getInstance().readTheme, shakeImgUp)
            ThemeManager.setReaderTheme(SettingManager.getInstance().readTheme, shakeImgDown)
            DisplayUtils.gone(night_mode_trans)
        }
    }

    override fun handleMsg(msg: Message?) {
        when (msg?.what) {
            HAND_ANIM_START -> setHandLineVisible(true)
            HAND_ANIM_END -> {
                setHandLineVisible(false)
                ARouterUtils.toActivity(ARouterConfig.BOOK_SHAKE)
            }
            else -> {
            }
        }
    }

    /**
     * 摇一摇手掌开合动画
     */
    private fun startShakeAnim() {
        mImgUp?.startAnimation(NeedForAnim.getInstance().getUpAnim(mHandler))
        mImgDn?.startAnimation(NeedForAnim.getInstance().downAnim)
    }

    /**
     * 手掌边线显示控制
     */
    private fun setHandLineVisible(isVisible: Boolean) {
        try {
            if (isVisible) {
                DisplayUtils.visible(mImgUpLine, mImgDnLine)
            } else {
                DisplayUtils.gone(mImgUpLine, mImgDnLine)
            }
        } catch (e: NullPointerException) {
        }
    }

    private fun queryUpdateBook() {
        //0:连载 1:完本
        if (TextUtils.equals(writingProcess, "1")) {
            book_status.text = "全本完"
        } else {
            DisplayUtils.visible(writing, notify_book_update)
            book_status.text = "待续未完"
            bookPresenter.queryUpdateBook(bookId, object : BaseObserver<ShakeBean>() {
                override fun onResponse(tBaseResult: BaseResult<ShakeBean>?, shakeBean: ShakeBean?, disposable: Disposable?) {
                    isNotifyUpdate = true
                    setDrawable()
                }

                override fun onError(code: Int, errDesc: String?) {
                    isNotifyUpdate = false
                    setDrawable()
                }
            })
        }
    }

    private fun addBookUpdate() {
        bookPresenter.addBookUpdate(bookId, object : Callback<ResponseBody> {
            override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>?) {
                isNotifyUpdate = true
                setDrawable()
                notify_book_update.isEnabled = true
            }

            override fun onFailure(call: Call<ResponseBody>?, t: Throwable?) {
                notify_book_update.isEnabled = true
            }
        })
    }

    private fun delBookUpdate() {
        bookPresenter.delBookUpdate(bookId, object : Callback<ResponseBody> {
            override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>?) {
                isNotifyUpdate = false
                setDrawable()
                notify_book_update.isEnabled = true
            }

            override fun onFailure(call: Call<ResponseBody>?, t: Throwable?) {
                notify_book_update.isEnabled = true
            }
        })
    }

    private fun setDrawable() {
        val drawable = if (isNotifyUpdate) {
            resources.getDrawable(R.mipmap.ic_choice_book_press)
        } else {
            resources.getDrawable(R.mipmap.ic_choice_book_nor)
        }
        drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
        notify_book_update.setCompoundDrawables(drawable, null, null, null)
    }

    /**
     *  获取猜你喜欢
     */
    private fun getBookLike() {
        bookPresenter.setBookLikeListView(this)
        bookPresenter.getBookLike(categoryId)
    }

    override fun showContent(t: BaseResult<List<BookInfo>>?) {
        t?.result?.data?.also {
            if (!Utils.isEmptyList(it)) {
                DisplayUtils.visible(like_book_tv)
                val bookLikeAdapter = BookLikeAdapter(mContext, it)
                RecyclerViewHelper.initRecyclerViewH(mContext, recycler_view, bookLikeAdapter)
            }
        }
    }

    override fun showError(errCode: Int, errDesc: String?) {
    }

    override fun showLoading(s: String?) {
    }

    override fun dismissLoading() {
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.notify_book_update -> {
                if (isNotifyUpdate) {
                    delBookUpdate()
                } else {
                    addBookUpdate()
                }
                notify_book_update.isEnabled = false
            }
            R.id.back_book_shelf -> {
                if (mContext is Activity) {
                    UrlRouter.from(mContext).jump("client://kanshu/main?tab_index=0")
                }
            }
            R.id.shakeDownIv, R.id.shakeUpIv -> {
                ARouterUtils.toActivity(ARouterConfig.BOOK_SHAKE)
            }
        }
    }

    fun stopShake() {
        mShakeListener?.stop()
    }

    fun destroy() {
        mShakeListener?.stop()
        mHandler?.removeCallbacksAndMessages(null)
    }

    fun startShake() {
        mShakeListener?.start()
    }

    class BookLikeAdapter(val context: Context, data: List<BookInfo>?) : BaseQuickAdapter<BookInfo>(context, data) {
        override fun attachLayoutRes(): Int {
            return R.layout.item_shelf_good_book
        }

        override fun convert(holder: BaseViewHolder, item: BookInfo?, position: Int) {
            item?.run {
                GlideImageLoader.load(cover_url, holder.getView(R.id.cover))
                holder.setText(R.id.book_title, book_title)
                holder.getView<ImageView>(R.id.cover).setOnClickListener {
                    ARouterUtils.toActivity(ARouterConfig.BOOK_DETAIL, "book_id", book_id)
                }
            }
        }
    }
}